<template>
  <div class="home-container">
    <!-- 顶部公告栏 -->
    <div class="announcement">
      <el-carousel height="30px" direction="vertical" :autoplay="true" :interval="3000">
        <el-carousel-item v-for="item in announcements" :key="item.id">
          <span class="announcement-title" @click="showAnnouncementDetail(item)">📢公告: {{ item.title }}</span>
        </el-carousel-item>
      </el-carousel>
    </div>
    
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="logo">
        <img src="@/assets/家教中心.png" alt="线上家教服务平台" class="logo-img">
        <span class="logo-text">线上家教服务平台</span>
      </div>
      <nav class="nav-menu">
        <a href="javascript:void(0)" @click="switchView('home')" :class="['nav-item', viewMode === 'home' ? 'active' : '']">首页</a>
        <a href="javascript:void(0)" @click="switchView('tutoring')" :class="['nav-item', viewMode === 'tutoring' ? 'active' : '']">家教广场</a>
        <a href="javascript:void(0)" @click="switchView('announcements')" :class="['nav-item', viewMode === 'announcements' ? 'active' : '']">系统公告</a>
        <a href="javascript:void(0)" @click="switchView('feedback')" :class="['nav-item', viewMode === 'feedback' ? 'active' : '']">留言反馈</a>
      </nav>
      <div class="user-info">
        <el-dropdown placement="bottom-end" @command="handleCommand">
          <span class="el-dropdown__box">
            <el-avatar :src="userInfo.userPic || avatar" class="user-avatar"></el-avatar>
            <span class="username">{{ userInfo.username }} <el-icon><CaretBottom /></el-icon></span>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="layout" :icon="Menu">导航栏</el-dropdown-item>
              <el-dropdown-item command="logout" :icon="SwitchButton">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </header>

    <!-- 主要内容区域 -->
    <main class="main-content">
      <div class="content-wrapper">
        <!-- 当查看家教广场时 -->
        <template v-if="viewMode === 'tutoring'">
          <!-- 家教广场标题 -->
          <div class="tutoring-header">
            <h2 class="main-title">家教广场</h2>
            <div class="tutoring-actions">
              <el-button type="warning" v-if="isFiltered" size="small" @click="resetTutoringFilter">查看全部家教</el-button>
              <el-button type="primary" v-if="tokenStore.userRole === 1" @click="becomeTutor">发布家教</el-button>
            </div>
          </div>

          <!-- 家教列表 -->
          <div class="tutoring-list">
            <div v-if="allTutorings.length === 0" class="empty-tutoring">
              <el-empty description="暂无家教信息" />
            </div>
            <div v-else class="tutoring-grid">
              <el-card v-for="tutor in allTutorings" :key="tutor.id" class="tutoring-card" :data-tutor-id="tutor.id">
                <div class="tutor-header">
                  <el-avatar :src="tutor.teacherAvatar || avatar" class="tutor-avatar"></el-avatar>
                  <div class="tutor-info">
                    <h3 class="tutor-name">{{ tutor.teacherName || '未知教师' }}</h3>
                    <div class="tutor-subjects">{{ tutor.subjects || '未知科目' }}</div>
                    <div class="tutor-edu" v-if="tutor.school">
                      <span>{{ tutor.school }}</span>
                      <span v-if="tutor.major">·{{ tutor.major }}</span>
                    </div>
                  </div>
                </div>
                <div class="tutor-description">{{ tutor.description || '暂无详细描述' }}</div>
                <div class="tutor-details">
                  <div class="detail-item">
                    <span class="detail-label">教育背景：</span>
                    <span>{{ tutor.education || '未知' }}</span>
                  </div>
                  <div class="detail-item">
                    <span class="detail-label">授课方式：</span>
                    <span>{{ tutor.teachingMethod || '未知' }}</span>
                  </div>
                  <div class="detail-item">
                    <span class="detail-label">课时费用：</span>
                    <span class="price">￥{{ tutor.hourlyRate || '面议' }}/小时</span>
                  </div>
                  <div class="detail-item">
                    <span class="detail-label">授课地点：</span>
                    <span>{{ tutor.location || '未指定' }}</span>
                  </div>
                  <div class="detail-item">
                    <span class="detail-label">可用时间：</span>
                    <span>{{ tutor.availableTime || '未指定' }}</span>
                  </div>
                </div>
                <div class="tutor-action-buttons">
                  <el-button type="primary" size="small" @click="showBookingDialog(tutor)">预约</el-button>
                  <el-button type="info" size="small" @click="showTutorDetail(tutor)">查看详情</el-button>
                </div>
              </el-card>
            </div>
          </div>
        </template>

        <!-- 当查看系统公告时 -->
        <template v-else-if="viewMode === 'announcements'">
          <div class="announcements-container">
            <div class="page-header">
              <h2 class="announcements-title">系统公告</h2>
              <p class="announcements-desc">查看平台最新通知和公告信息</p>
            </div>

            <!-- 公告列表 -->
            <div class="announcements-list-container">
              <div class="list-header">
                <h3>公告列表</h3>
                <el-button type="primary" size="small" plain @click="getAnnouncements">刷新</el-button>
              </div>

              <el-empty v-if="announcements.length === 0" description="暂无公告"></el-empty>

              <div v-else class="announcements-list">
                <el-timeline>
                  <el-timeline-item
                    v-for="item in announcements"
                    :key="item.id"
                    :timestamp="formatDate(item.createTime)"
                    type="primary"
                  >
                    <el-card class="announcement-card">
                      <template #header>
                        <div class="card-header">
                          <span class="announcement-card-title">{{ item.title }}</span>
                        </div>
                      </template>
                      <div class="announcement-card-content">{{ item.content }}</div>
                      <div class="announcement-card-footer">
                        <span>发布人: {{ item.createUserName }}</span>
                      </div>
                    </el-card>
                  </el-timeline-item>
                </el-timeline>
              </div>
            </div>
          </div>
        </template>

        <!-- 当查看首页内容时 -->
        <template v-else-if="viewMode === 'home'">
          <!-- 当没有选中分类时显示首页内容 -->
          <template v-if="!selectedCategory">
            <!-- 学科分类区域 -->
            <div class="subject-categories">
              <h2 class="section-title">课程分类</h2>
              <el-skeleton :loading="loading" animated :count="6" :throttle="500">
                <template #template>
                  <div class="categories-container">
                    <div class="category-item skeleton" v-for="i in 6" :key="i">
                      <div class="subject-icon skeleton-icon"></div>
                      <div class="category-info">
                        <div class="skeleton-text"></div>
                        <div class="skeleton-text-sm"></div>
                      </div>
                    </div>
                  </div>
                </template>
                <template #default>
                  <div class="categories-container" v-if="categories.length > 0">
                    <div class="category-item" v-for="category in categories" :key="category.id" @click="navigateToCategory(category.id)">
                      <div class="subject-icon">
                        <el-image :src="category.categoryImage" fit="cover" :preview="false">
                          <template #error>
                            <div class="image-error">
                              <el-icon><PictureFilled /></el-icon>
                            </div>
                          </template>
                        </el-image>
                      </div>
                      <div class="category-info">
                        <span class="category-name">{{ category.categoryName }}</span>
                        <span class="category-alias">{{ category.categoryAlias }}</span>
                      </div>
                    </div>
                  </div>
                  <div v-else class="empty-categories">
                    <el-empty description="暂无分类数据" />
                  </div>
                </template>
              </el-skeleton>
              <div v-if="errorMsg" class="error-message">
                <el-alert :title="errorMsg" type="warning" show-icon :closable="false" />
              </div>
            </div>

            <!-- 平台教师展示区域-->
            <div class="platform-teachers-right">
              <h2 class="section-title">热门家教</h2>
              <div class="teachers-list">
                <div v-if="latestTutorings.length === 0">
                  <el-empty description="暂无家教信息" />
                </div>
                <div class="teacher-card" v-for="tutor in latestTutorings" :key="tutor.id" @click="viewTeacherDetails(tutor)">
                  <div class="teacher-avatar">
                    <el-avatar :src="tutor.teacherAvatar || avatar" class="teacher-avatar-img"></el-avatar>
                  </div>
                  <p class="teacher-name">{{ tutor.teacherName || '未知教师' }}</p>
                  <p class="teacher-subject">{{ tutor.subjects || '未知科目' }}</p>
                </div>
              </div>
            </div>

            <!-- 中间轮播图区域 -->
            <div class="banner-section">
              <el-carousel :interval="4000" type="card" height="300px" class="banner-container">
                <el-carousel-item v-for="banner in banners" :key="banner.id">
                  <el-image 
                    :src="banner.imageUrl" 
                    fit="cover"
                    class="banner-image"
                    :alt="banner.title"
                  >
                    <template #error>
                      <div class="banner-placeholder">
                        <div class="banner-text">
                          <h2>{{ banner.title }}</h2>
                        </div>
                      </div>
                    </template>
                  </el-image>
                </el-carousel-item>
              </el-carousel>
            </div>

            <!-- 请家教/做家教按钮区域 -->
            <div class="action-buttons">
              <div class="action-button request-tutor" @click="requestTutor">
                <h3>请家教</h3>
              </div>
              <div class="action-button become-tutor" @click="becomeTutor">
                <h3>做家教</h3>
              </div>
            </div>

            

            <!-- 平台统计数据 -->
            <div class="platform-stats">
              <h2 class="section-title">平台数据</h2>
              <div class="stats-container">
                <div class="stat-item">
                  <div class="stat-value">{{ platformStats.teacherCount }}</div>
                  <div class="stat-label">认证教师</div>
                </div>
                <div class="stat-item">
                  <div class="stat-value">{{ platformStats.studentCount }}</div>
                  <div class="stat-label">注册学生</div>
                </div>
                <div class="stat-item">
                  <div class="stat-value">{{ platformStats.tutoringCount }}</div>
                  <div class="stat-label">家教信息</div>
                </div>
                <div class="stat-item">
                  <div class="stat-value">{{ platformStats.completedTutoringCount }}</div>
                  <div class="stat-label">已完成家教</div>
                </div>
              </div>
            </div>
          </template>

          <!-- 当选中分类时只显示分类视频区域 -->
          <template v-else>
            <!-- 分类视频展示区域 -->
            <div class="category-videos-section">
              <h2 class="section-title">{{ selectedCategoryName }} 课程视频</h2>
              
              <div v-if="categoryVideosLoading" class="loading-container">
                <el-skeleton :rows="3" animated />
              </div>
              
              <div v-else-if="categoryVideos.length === 0" class="empty-videos">
                <el-empty description="暂无相关视频" />
              </div>
              
              <div v-else class="lesson-grid">
                <el-card 
                  v-for="video in categoryVideos" 
                  :key="video.id" 
                  class="lesson-card"
                  @click="showVideoDetail(video)"
                >
                  <div class="lesson-cover">
                    <img :src="video.coverImg" :alt="video.title">
                    <div class="play-icon">
                      <el-icon><VideoPlay /></el-icon>
                    </div>
                  </div>
                  <div class="lesson-info">
                    <h3 class="lesson-title">{{ video.title }}</h3>
                    <div class="lesson-meta">
                      <span>{{ video.categoryName }}</span>
                      <span>{{ video.createUserName }}</span>
                    </div>
                    <div class="lesson-stats">
                      <span class="stat-item">
                        <el-icon><Collection /></el-icon>
                        {{ video.likeCount || 0 }}
                      </span>
                      <span class="stat-item">
                        <el-icon><Star /></el-icon>
                        {{ video.favoriteCount || 0 }}
                      </span>
                    </div>
                  </div>
                </el-card>
              </div>
            </div>
          </template>
        </template>

        <!-- 当查看留言反馈时 -->
        <template v-else-if="viewMode === 'feedback'">
          <div class="feedback-container">
            <div class="page-header">
              <h2 class="feedback-title">留言反馈</h2>
              <p class="feedback-desc">欢迎提出您的宝贵意见和建议，我们将认真考虑每一条反馈</p>
            </div>
    
            <!-- 留言表单 -->
            <div class="feedback-form-container">
              <el-form :model="feedbackForm" :rules="feedbackRules" ref="feedbackFormRef" label-width="100px">
                <el-form-item label="留言内容" prop="content">
                  <el-input type="textarea" v-model="feedbackForm.content" :rows="4" placeholder="请输入您的意见、建议或问题..."></el-input>
                </el-form-item>
                <el-form-item label="联系方式" prop="contactInfo">
                  <el-input v-model="feedbackForm.contactInfo" placeholder="选填，方便我们与您联系（手机号/邮箱/微信等）"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="submitFeedback" :loading="feedbackSubmitting">提交留言</el-button>
                  <el-button @click="resetFeedbackForm">重置</el-button>
                </el-form-item>
              </el-form>
            </div>
    
            <!-- 历史留言 -->
            <div class="feedback-history">
              <div class="history-header">
                <h3>我的留言历史</h3>
                <el-button type="primary" size="small" plain @click="fetchMyFeedbacks">刷新</el-button>
              </div>
    
              <el-empty v-if="myFeedbacks.length === 0" description="暂无留言记录"></el-empty>
    
              <div v-else class="feedback-list">
                <el-timeline>
                  <el-timeline-item
                    v-for="item in myFeedbacks"
                    :key="item.id"
                    :timestamp="item.createTime"
                    :type="item.status === 1 ? 'success' : 'primary'"
                  >
                    <el-card class="feedback-card">
                      <template #header>
                        <div class="card-header">
                          <span>留言内容</span>
                          <el-tag v-if="item.status === 1" type="success">已回复</el-tag>
                          <el-tag v-else type="info">待处理</el-tag>
                        </div>
                      </template>
                      <div class="feedback-content">{{ item.content }}</div>
                      
                      <!-- 管理员回复 -->
                      <div v-if="item.status === 1" class="feedback-reply">
                        <div class="reply-header">
                          <span class="reply-title">管理员回复</span>
                          <span class="reply-time">{{ item.replyTime }}</span>
                        </div>
                        <div class="reply-content">{{ item.reply }}</div>
                        <div class="reply-footer">回复人: {{ item.replyUsername }}</div>
                      </div>
    
                      <!-- 删除按钮 -->
                      <div class="feedback-actions">
                        <el-popconfirm
                          title="确定要删除此条留言吗？"
                          @confirm="deleteFeedbackItem(item.id)"
                        >
                          <template #reference>
                            <el-button type="danger" size="small" text>删除</el-button>
                          </template>
                        </el-popconfirm>
                      </div>
                    </el-card>
                  </el-timeline-item>
                </el-timeline>
              </div>
            </div>
          </div>
        </template>

        <!-- 视频详情对话框 -->
        <el-dialog v-model="dialogVisible" :title="currentVideo.title" width="70%" destroy-on-close>
          <template v-if="currentVideo">
            <div class="video-detail">
              <div class="detail-meta">
                <span>分类：{{ currentVideo.categoryName }}</span>
                <span>作者：{{ currentVideo.createUserName }}</span>
                <span v-if="currentVideo.createTime">发布时间：{{ currentVideo.createTime }}</span>
              </div>
              <div class="video-player-container">
                <video 
                  ref="videoPlayer" 
                  controls 
                  class="video-player" 
                  :src="currentVideo.videoUrl"
                  @ended="videoEnded"
                ></video>
              </div>
              <div class="detail-content" v-if="currentVideo.content" v-html="currentVideo.content"></div>
            </div>
          </template>
        </el-dialog>

        <!-- 公告详情对话框 -->
        <el-dialog
          v-model="dialogVisibleAnnouncement"
          :title="currentAnnouncement.title"
          width="50%"
          :close-on-click-modal="false"
        >
          <div class="announcement-detail">
            <div class="announcement-meta">
              <span>发布人：{{ currentAnnouncement.createUserName }}</span>
              <span>发布时间：{{ formatDate(currentAnnouncement.createTime) }}</span>
            </div>
            <div class="announcement-content">{{ currentAnnouncement.content }}</div>
          </div>
        </el-dialog>

        <!-- 老师详情对话框 -->
        <el-dialog
          v-model="tutorDialogVisible"
          :title="currentTutor.teacherName || '教师详情'"
          width="60%"
          :close-on-click-modal="false"
        >
          <div class="tutor-detail-dialog">
            <div class="tutor-detail-header">
              <el-avatar :src="currentTutor.teacherAvatar || avatar" class="tutor-detail-avatar"></el-avatar>
              <div class="tutor-detail-info">
                <h2 class="tutor-detail-name">{{ currentTutor.teacherName || '未知教师' }}</h2>
                <div class="tutor-detail-subjects">{{ currentTutor.subjects || '未知科目' }}</div>
                <div class="tutor-detail-edu" v-if="currentTutor.school">
                  <span>{{ currentTutor.school }}</span>
                  <span v-if="currentTutor.major">·{{ currentTutor.major }}</span>
                </div>
              </div>
            </div>
            
            <div class="tutor-detail-section">
              <h3 class="section-subtitle">教师介绍</h3>
              <p class="tutor-detail-description">{{ currentTutor.description || '暂无详细描述' }}</p>
            </div>
            
            <div class="tutor-detail-section">
              <h3 class="section-subtitle">详细信息</h3>
              <div class="tutor-detail-item">
                <span class="detail-label">教育背景：</span>
                <span>{{ currentTutor.education || '未知' }}</span>
              </div>
              <div class="tutor-detail-item">
                <span class="detail-label">授课方式：</span>
                <span>{{ currentTutor.teachingMethod || '未知' }}</span>
              </div>
              <div class="tutor-detail-item">
                <span class="detail-label">课时费用：</span>
                <span class="price">￥{{ currentTutor.hourlyRate || '面议' }}/小时</span>
              </div>
              <div class="tutor-detail-item">
                <span class="detail-label">授课地点：</span>
                <span>{{ currentTutor.location || '未指定' }}</span>
              </div>
              <div class="tutor-detail-item">
                <span class="detail-label">可用时间：</span>
                <span>{{ currentTutor.availableTime || '未指定' }}</span>
              </div>
            </div>
            
            <div class="tutor-detail-section" v-if="currentTutor.achievements">
              <h3 class="section-subtitle">教学成果</h3>
              <p>{{ currentTutor.achievements }}</p>
            </div>
            
            <div class="tutor-detail-section" v-if="currentTutor.preferredStudents">
              <h3 class="section-subtitle">教学对象</h3>
              <p>{{ currentTutor.preferredStudents }}</p>
            </div>
            
            <div class="tutor-detail-actions">
              <el-button type="primary" @click="showBookingDialog(currentTutor)">预约</el-button>
            </div>
          </div>
        </el-dialog>

        <!-- 预约对话框 -->
        <el-dialog v-model="bookingDialogVisible" title="预约家教" width="500px">
            <el-form :model="bookingForm" :rules="bookingRules" ref="bookingFormRef" label-width="100px">
                <el-form-item label="开始时间" prop="startTime">
                    <el-date-picker
                        v-model="bookingForm.startTime"
                        type="datetime"
                        placeholder="选择开始时间"
                    />
                </el-form-item>
                <el-form-item label="结束时间" prop="endTime">
                    <el-date-picker
                        v-model="bookingForm.endTime"
                        type="datetime"
                        placeholder="选择结束时间"
                    />
                </el-form-item>
                <el-form-item label="上课地点" prop="location">
                    <el-input v-model="bookingForm.location" placeholder="请输入上课地点" />
                </el-form-item>
                <el-form-item label="具体要求" prop="requirements">
                    <el-input
                        v-model="bookingForm.requirements"
                        type="textarea"
                        placeholder="请输入具体要求"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="bookingDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitBooking">提交预约</el-button>
                </span>
            </template>
        </el-dialog>
      </div>
    </main>

    <!-- 底部区域 -->
    <footer class="footer">
      <p>© 2025 中小学生家教服务平台 版权所有</p>
    </footer>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onBeforeUnmount } from 'vue';
import { useRouter } from 'vue-router';
import { CaretBottom, PictureFilled, VideoCameraFilled, VideoPlay, Collection, Star, ArrowLeft, Menu, SwitchButton } from '@element-plus/icons-vue';
import useUserInfoStore from '@/stores/userInfo';
import { useTokenStore } from '@/stores/token';
import avatar from '@/assets/default.png';
import { lessonCategoryListService, lessonListService } from '@/api/lesson.js';
import { ElMessage, ElMessageBox } from 'element-plus';
import request from '@/utils/request';
import { announcementPublishedService } from '@/api/announcement.js';
import { tutoringService } from '@/api/tutoring';
import { addFeedbackService, getMyFeedbacksService, deleteFeedbackService } from '@/api/feedback';

const router = useRouter();
const userInfoStore = useUserInfoStore();
const tokenStore = useTokenStore();
const userInfo = userInfoStore.info;

// 定义API基础URL
const baseURL = '/api';

// 课程分类数据
const categories = ref([]);
// 加载状态
const loading = ref(false);
// 错误信息
const errorMsg = ref('');

// 默认分类数据（当API调用失败时使用）
const defaultCategories = [
  {
    id: 1,
    categoryName: '数学',
    categoryAlias: '初高中数学、高等数学',
    categoryImage: 'https://via.placeholder.com/60x60?text=数学'
  },
  {
    id: 2,
    categoryName: '英语',
    categoryAlias: '英语口语、写作、阅读',
    categoryImage: 'https://via.placeholder.com/60x60?text=英语'
  },
  {
    id: 3,
    categoryName: '物理',
    categoryAlias: '力学、电磁学、现代物理',
    categoryImage: 'https://via.placeholder.com/60x60?text=物理'
  },
  {
    id: 4,
    categoryName: '化学',
    categoryAlias: '有机化学、无机化学',
    categoryImage: 'https://via.placeholder.com/60x60?text=化学'
  },
  {
    id: 5,
    categoryName: '生物',
    categoryAlias: '动植物学、微生物学',
    categoryImage: 'https://via.placeholder.com/60x60?text=生物'
  },
  {
    id: 6,
    categoryName: '历史',
    categoryAlias: '中国历史、世界历史',
    categoryImage: 'https://via.placeholder.com/60x60?text=历史'
  }
];

// 直接获取课程分类列表，不需要身份验证
const fetchCategoriesDirectly = async () => {
  loading.value = true;
  errorMsg.value = '';
  
  try {
    console.log('开始直接获取课程分类数据...');
    // 使用完整的API基础URL
    const apiUrl = `${baseURL}/category`;
    console.log('请求URL:', apiUrl);
    
    // 创建一个不带认证信息的axios实例
    const response = await request.get(apiUrl, { 
      withCredentials: false,
      headers: { 'Content-Type': 'application/json' }
    });
    
    console.log('直接获取课程分类结果:', response);
    
    if (response.status === 200 && response.data.code === 0) {
      if (response.data.data && response.data.data.length > 0) {
        categories.value = response.data.data;
        console.log('成功获取课程分类数据:', categories.value);
      } else {
        console.warn('课程分类数据为空，使用默认数据');
        categories.value = defaultCategories;
        ElMessage.info('暂无课程分类数据，显示默认分类');
      }
    } else {
      console.error('获取课程分类失败:', response.data?.msg || '未知错误');
      errorMsg.value = response.data?.msg || '获取课程分类失败';
      categories.value = defaultCategories;
      ElMessage.warning(errorMsg.value + '，显示默认分类');
    }
  } catch (error) {
    console.error('获取课程分类异常:', error);
    console.error('错误详情:', error.response || error.message || error);
    errorMsg.value = '网络异常，无法获取课程分类';
    categories.value = defaultCategories;
    ElMessage.warning(errorMsg.value + '，显示默认分类');
  } finally {
    loading.value = false;
  }
};

// 使用服务获取课程分类列表（需要身份验证）
const fetchCategories = async () => {
  loading.value = true;
  errorMsg.value = '';
  
  try {
    console.log('开始获取课程分类数据...');
    // 检查是否有token
    if (!tokenStore.token) {
      console.warn('未登录状态，尝试直接获取分类数据');
      await fetchCategoriesDirectly();
      return;
    }
    
    try {
      const result = await lessonCategoryListService();
      console.log('获取课程分类结果:', result);
      
      if (result && result.code === 0) {
        if (result.data && result.data.length > 0) {
          categories.value = result.data;
          console.log('成功获取课程分类数据:', categories.value);
        } else {
          console.warn('课程分类数据为空，使用默认数据');
          categories.value = defaultCategories;
          ElMessage.info('暂无课程分类数据，显示默认分类');
        }
      } else {
        console.error('获取课程分类失败:', result?.msg || '未知错误');
        // 如果是401错误，尝试直接获取
        if (result?.code === 401) {
          console.warn('身份验证失败，尝试直接获取分类数据');
          await fetchCategoriesDirectly();
        } else {
          errorMsg.value = result?.msg || '获取课程分类失败';
          categories.value = defaultCategories;
          ElMessage.warning(errorMsg.value + '，显示默认分类');
        }
      }
    } catch (serviceError) {
      console.error('服务调用异常:', serviceError);
      // 如果是401错误，尝试直接获取
      if (serviceError.response && serviceError.response.status === 401) {
        console.warn('身份验证失败，尝试直接获取分类数据');
        await fetchCategoriesDirectly();
      } else {
        // 尝试直接获取数据作为备选方案
        console.warn('服务调用失败，尝试直接获取分类数据');
        await fetchCategoriesDirectly();
      }
    }
  } catch (error) {
    console.error('获取课程分类异常:', error);
    errorMsg.value = '网络异常，无法获取课程分类';
    categories.value = defaultCategories;
    ElMessage.warning(errorMsg.value + '，显示默认分类');
  } finally {
    loading.value = false;
  }
};

// 添加选中的分类ID和名称
const selectedCategory = ref(null);
const selectedCategoryName = ref('');

// 分类视频数据
const categoryVideos = ref([]);
// 视频对话框可见性
const dialogVisible = ref(false);
// 当前播放的视频
const currentVideo = ref({});
// 视频播放器引用
const videoPlayer = ref(null);
// 视频加载状态
const categoryVideosLoading = ref(false);

// 获取分类视频
const fetchCategoryVideos = async (categoryId) => {
  try {
    // 显示加载状态
    categoryVideosLoading.value = true;
    
    // 调用后端API获取视频数据
    console.log('获取分类视频，分类ID:', categoryId);
    
    const params = {
      pageNum: 1,
      pageSize: 9, // 一次显示9个视频
      categoryId: categoryId,
      state: '已发布' // 只显示已发布的视频
    };
    
    const result = await lessonListService(params);
    
    if (result.code === 0 && result.data && result.data.items) {
      categoryVideos.value = result.data.items;
      console.log('获取到的视频数据:', categoryVideos.value);
      
      if (categoryVideos.value.length === 0) {
        ElMessage.info('该分类暂无视频');
      }
    } else {
      console.error('获取视频数据失败:', result.msg || '未知错误');
      ElMessage.error('获取视频数据失败');
      categoryVideos.value = [];
      
      // 如果API调用失败，使用模拟数据
      if (defaultVideos[categoryId]) {
        categoryVideos.value = defaultVideos[categoryId];
        ElMessage.info('使用模拟数据显示');
      }
    }
  } catch (error) {
    console.error('获取分类视频失败:', error);
    ElMessage.error('获取视频失败');
    categoryVideos.value = [];
    
    // 如果API调用失败，使用模拟数据
    if (defaultVideos[categoryId]) {
      categoryVideos.value = defaultVideos[categoryId];
      ElMessage.info('使用模拟数据显示');
    }
  } finally {
    categoryVideosLoading.value = false;
  }
};

// 显示视频详情
const showVideoDetail = (video) => {
  currentVideo.value = video;
  dialogVisible.value = true;
  
  // 确保视频加载后自动播放
  setTimeout(() => {
    if (videoPlayer.value) {
      videoPlayer.value.play().catch(e => {
        console.warn('自动播放失败，可能需要用户交互:', e);
      });
    }
  }, 300);
};

// 视频播放结束
const videoEnded = () => {
  console.log('视频播放结束');
  // 可以在这里添加视频结束后的逻辑，比如推荐下一个视频
};

// 添加默认视频数据（模拟数据）
const defaultVideos = {
  1: [
    { 
      id: 1, 
      title: '数学基础课程 - 代数入门', 
      description: '适合初中学生的代数基础课程', 
      coverImg: 'https://via.placeholder.com/300x200?text=数学视频',
      videoUrl: 'https://www.w3schools.com/html/mov_bbb.mp4',
      categoryName: '数学',
      createUserName: '张老师',
      likeCount: 120,
      favoriteCount: 45
    },
    { 
      id: 2, 
      title: '数学进阶 - 几何证明', 
      description: '高中几何证明方法详解', 
      coverImg: 'https://via.placeholder.com/300x200?text=几何视频',
      videoUrl: 'https://www.w3schools.com/html/mov_bbb.mp4',
      categoryName: '数学',
      createUserName: '李老师',
      likeCount: 98,
      favoriteCount: 32
    },
    { 
      id: 3, 
      title: '高等数学预备课程', 
      description: '为大学数学打基础', 
      coverImg: 'https://via.placeholder.com/300x200?text=高数视频',
      videoUrl: 'https://www.w3schools.com/html/mov_bbb.mp4',
      categoryName: '数学',
      createUserName: '王教授',
      likeCount: 156,
      favoriteCount: 67
    }
  ],
};

// 跳转到分类详情页 - 修改为显示分类视频
const navigateToCategory = (categoryId) => {
  // 获取分类名称
  const category = categories.value.find(c => c.id === categoryId);
  const categoryName = category ? category.categoryName : '';
  
  // 设置选中的分类ID和名称
  selectedCategory.value = categoryId;
  selectedCategoryName.value = categoryName;
  
  // 获取该分类的课程
  fetchCategoryVideos(categoryId);
  
  // 添加历史记录状态，便于后退处理
  window.history.pushState({ view: 'category', categoryId }, '', window.location.href);
  
  // 滚动到视频区域
  setTimeout(() => {
    const videoSection = document.querySelector('.category-videos-section');
    if (videoSection) {
      videoSection.scrollIntoView({ behavior: 'smooth' });
    }
  }, 100);
};

// 跳转到登录页面
const goToLogin = () => {
  router.push('/login');
};

// 请家教
const requestTutor = () => {
  if (!tokenStore.token) {
    ElMessage.warning('请先登录');
    goToLogin();
    return;
  }
  // 切换到家教广场视图
  switchView('tutoring');
};

// 做家教
const becomeTutor = () => {
  if (!tokenStore.token) {
    ElMessage.warning('请先登录');
    goToLogin();
    return;
  }
  
  // 检查用户角色
  if (tokenStore.userRole !== 1) {
    ElMessage.warning('只有教师身份才能发布家教信息');
    return;
  }
  
  // 跳转到发布家教信息页面
  router.push('/tutoring/publish');
};

// 添加返回首页方法
const backToHome = () => {
  selectedCategory.value = null;
  selectedCategoryName.value = '';
  categoryVideos.value = [];
  
  // 添加历史记录状态，便于后退处理
  window.history.pushState({ view: 'home' }, '', window.location.href);
};

// 添加轮播图数据
const banners = ref([]);
const getBanners = async () => {
    try {
        const response = await request.get('/banner/active');
        if (response.code === 0) {
            banners.value = response.data;
            console.log('获取到的轮播图数据:', banners.value);
        } else {
            console.error('获取轮播图失败:', response.msg);
            // 使用默认数据
            banners.value = [
                {
                    id: 1,
                    title: '开学季',
                    imageUrl: 'https://via.placeholder.com/1200x300',
                    link: '#'
                },
                {
                    id: 2,
                    title: '优秀教师推荐',
                    imageUrl: 'https://via.placeholder.com/1200x300',
                    link: '#'
                }
            ];
        }
    } catch (error) {
        console.error('获取轮播图异常:', error);
        // 使用默认数据
        banners.value = [
            {
                id: 1,
                title: '开学季',
                imageUrl: 'https://via.placeholder.com/1200x300',
                link: '#'
            },
            {
                id: 2,
                title: '优秀教师推荐',
                imageUrl: 'https://via.placeholder.com/1200x300',
                link: '#'
            }
        ];
    }
};

// 公告数据
const announcements = ref([])

// 平台统计数据
const platformStats = ref({
  teacherCount: 0,
  studentCount: 0,
  tutoringCount: 0,
  completedTutoringCount: 0
});

// 最新家教信息
const latestTutorings = ref([]);

// 获取公告数据
const getAnnouncements = async () => {
  try {
    const res = await announcementPublishedService()
    if (res.code === 0) {
      announcements.value = res.data
    }
  } catch (error) {
    console.error('获取公告失败:', error)
  }
}

// 获取平台统计数据
const getPlatformStats = async () => {
  try {
    const res = await request.get('/api/home/stats');
    if (res.code === 0) {
      platformStats.value = res.data;
      console.log('获取平台统计数据成功:', platformStats.value);
    } else {
      console.error('获取平台统计数据失败:', res.msg);
    }
  } catch (error) {
    console.error('获取平台统计数据异常:', error);
  }
};

// 获取最新家教信息
const getLatestTutorings = async () => {
  try {
    const res = await tutoringService.getAllTutoring();
    if (res.code === 0) {
      // 只显示最新的5条家教信息
      latestTutorings.value = res.data.slice(0, 5);
      console.log('获取最新家教信息成功:', latestTutorings.value);
    } else {
      console.error('获取最新家教信息失败:', res.msg);
    }
  } catch (error) {
    console.error('获取最新家教信息异常:', error);
  }
};

// 视图模式：home-首页, tutoring-家教广场, feedback-留言反馈
const viewMode = ref('home');

// 所有家教信息
const allTutorings = ref([]);

// 是否已筛选
const isFiltered = ref(false);

// 切换视图
const switchView = (mode) => {
  viewMode.value = mode;
  
  // 如果切换到家教广场，获取所有家教信息
  if (mode === 'tutoring') {
    if (!isFiltered.value) {
      getAllTutorings();
    }
    
    // 添加历史记录状态，便于后退处理
    window.history.pushState({ view: 'tutoring' }, '', window.location.href);
  }

  // 如果切换到留言反馈，获取我的留言列表
  if (mode === 'feedback') {
    fetchMyFeedbacks();
    
    // 添加历史记录状态，便于后退处理
    window.history.pushState({ view: 'feedback' }, '', window.location.href);
  }

  // 如果切换到系统公告，获取公告列表
  if (mode === 'announcements') {
    getAnnouncements();
    
    // 添加历史记录状态，便于后退处理
    window.history.pushState({ view: 'announcements' }, '', window.location.href);
  }

  // 重置选中的分类
  if (mode === 'home') {
    selectedCategory.value = null;
    selectedCategoryName.value = '';
    
    // 添加历史记录状态，便于后退处理
    window.history.pushState({ view: 'home' }, '', window.location.href);
  }

  // 滚动到顶部
  window.scrollTo(0, 0);
};

// 重置家教筛选
const resetTutoringFilter = () => {
  getAllTutorings();
  isFiltered.value = false;
};

// 获取所有家教信息
const getAllTutorings = async () => {
  try {
    const res = await tutoringService.getAllTutoring();
    if (res.code === 0) {
      allTutorings.value = res.data;
      console.log('获取所有家教信息成功:', allTutorings.value);
    } else {
      console.error('获取所有家教信息失败:', res.msg);
      ElMessage.error('获取家教信息失败');
    }
  } catch (error) {
    console.error('获取所有家教信息异常:', error);
    ElMessage.error('网络异常，获取家教信息失败');
  }
};

// 根据教师ID获取家教信息
const getTutoringByTeacherId = async (teacherId) => {
  try {
    const res = await tutoringService.getAllTutoring();
    if (res.code === 0) {
      // 筛选该教师发布的家教信息
      allTutorings.value = res.data.filter(item => item.teacherId === teacherId);
      isFiltered.value = true;
      console.log('获取教师家教信息成功:', allTutorings.value);
      
      if (allTutorings.value.length === 0) {
        ElMessage.info('该教师暂无家教信息');
      }
    } else {
      console.error('获取教师家教信息失败:', res.msg);
      ElMessage.error('获取教师家教信息失败');
    }
  } catch (error) {
    console.error('获取教师家教信息异常:', error);
    ElMessage.error('网络异常，获取教师家教信息失败');
  }
};

// 根据ID请求特定家教
const requestTutorById = (id) => {
  // 已被showBookingDialog替代，保留此函数以防其他地方引用
  showBookingDialog({id: id});
};

// 查看教师详情
const viewTeacherDetails = (tutor) => {
  // 切换到家教广场视图
  switchView('tutoring');
  
  // 获取该教师的家教信息
  getTutoringByTeacherId(tutor.teacherId);
};

// 公告详情对话框
const dialogVisibleAnnouncement = ref(false)
const currentAnnouncement = ref({})

// 显示公告详情
const showAnnouncementDetail = (announcement) => {
  currentAnnouncement.value = announcement
  dialogVisibleAnnouncement.value = true
}

// 老师详情对话框
const tutorDialogVisible = ref(false)
const currentTutor = ref({})

// 显示老师详情
const showTutorDetail = (tutor) => {
  currentTutor.value = tutor
  tutorDialogVisible.value = true
}

// 处理浏览器后退按钮
const handlePopState = (event) => {
  console.log('检测到浏览器回退操作', event.state);
  
  // 根据历史记录中的状态处理回退
  const state = event.state || {};
  
  if (state.view === 'home' || !state.view) {
    // 如果回退到首页状态或无状态，直接设置为首页视图
    backToHomePage();
  } else if (state.view === 'tutoring') {
    // 如果回退到家教广场状态
    if (viewMode.value !== 'tutoring') {
      switchView('tutoring');
    }
  } else if (state.view === 'feedback') {
    // 如果回退到留言反馈状态
    if (viewMode.value !== 'feedback') {
      switchView('feedback');
    }
  } else if (state.view === 'announcements') {
    // 如果回退到系统公告状态
    if (viewMode.value !== 'announcements') {
      switchView('announcements');
    }
  } else if (state.view === 'category' && state.categoryId) {
    // 如果回退到分类详情状态
    if (selectedCategory.value !== state.categoryId) {
      navigateToCategory(state.categoryId);
    }
  } else {
    // 默认行为，回到首页
    backToHomePage();
  }
  
  // 更新历史记录，防止继续回退出页面
  window.history.pushState(state, '', window.location.href);
};

// 返回首页视图
const backToHomePage = () => {
  // 重置所有状态
  viewMode.value = 'home';
  selectedCategory.value = null;
  selectedCategoryName.value = '';
  categoryVideos.value = [];
  isFiltered.value = false;
  
  // 滚动到顶部
  window.scrollTo(0, 0);
};

// 修改处理下拉菜单命令的方法
const handleCommand = (command) => {
  if (command === 'logout') {
    ElMessageBox.confirm(
      '您确认要退出吗?',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(async () => {
        // 退出登录
        console.log('用户确认退出登录');
        // 1.清空pinia中存储的token以及个人信息
        tokenStore.removeToken()
        userInfoStore.removeInfo()

        // 2.跳转到登录页面
        router.push('/login')
        ElMessage({
          type: 'success',
          message: '退出登录成功',
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '用户取消了退出登录',
        })
      })
  } else if (command === 'layout') {
    // 检查是否已登录
    if (!tokenStore.token) {
      ElMessage.warning('请先登录');
      router.push('/login');
      return;
    }
    // 导航到根路由，显示Layout页面
    router.push('/');
  }
}

// 添加留言反馈数据和方法
const feedbackFormRef = ref(null);
const feedbackForm = ref({
  content: '',
  contactInfo: ''
});

// 表单验证规则
const feedbackRules = {
  content: [
    { required: true, message: '请输入留言内容', trigger: 'blur' },
    { min: 5, max: 500, message: '内容长度应在 5 到 500 个字符之间', trigger: 'blur' }
  ]
};

// 提交状态
const feedbackSubmitting = ref(false);

// 历史留言
const myFeedbacks = ref([]);
const feedbackLoading = ref(false);

// 提交留言
const submitFeedback = () => {
  // 检查是否登录
  if (!tokenStore.token) {
    ElMessage.warning('请先登录');
    goToLogin();
    return;
  }

  feedbackFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    try {
      feedbackSubmitting.value = true;
      const res = await addFeedbackService(feedbackForm.value);
      
      if (res.code === 0) {
        ElMessage.success('留言提交成功');
        resetFeedbackForm();
        // 刷新留言列表
        fetchMyFeedbacks();
      } else {
        ElMessage.error(res.msg || '提交失败');
      }
    } catch (error) {
      console.error('提交留言失败:', error);
      ElMessage.error('提交失败，请稍后再试');
    } finally {
      feedbackSubmitting.value = false;
    }
  });
};

// 重置表单
const resetFeedbackForm = () => {
  feedbackFormRef.value.resetFields();
};

// 获取我的留言列表
const fetchMyFeedbacks = async () => {
  // 检查是否登录
  if (!tokenStore.token) {
    return;
  }

  try {
    feedbackLoading.value = true;
    const res = await getMyFeedbacksService();
    
    if (res.code === 0) {
      myFeedbacks.value = res.data;
    } else {
      ElMessage.error(res.msg || '获取留言列表失败');
    }
  } catch (error) {
    console.error('获取留言列表失败:', error);
    ElMessage.error('获取留言列表失败，请稍后再试');
  } finally {
    feedbackLoading.value = false;
  }
};

// 删除留言
const deleteFeedbackItem = async (id) => {
  try {
    const res = await deleteFeedbackService(id);
    
    if (res.code === 0) {
      ElMessage.success('删除成功');
      // 刷新留言列表
      fetchMyFeedbacks();
    } else {
      ElMessage.error(res.msg || '删除失败');
    }
  } catch (error) {
    console.error('删除留言失败:', error);
    ElMessage.error('删除失败，请稍后再试');
  }
};

onMounted(() => {
    // 页面加载时获取数据
    fetchCategories();
    getBanners();
    getAnnouncements();
    getPlatformStats();
    getLatestTutorings();
    
    // 添加初始历史记录状态
    window.history.pushState({ view: 'home' }, '', window.location.href);
    
    // 监听浏览器后退按钮
    window.addEventListener('popstate', handlePopState);
});

onBeforeUnmount(() => {
  // 组件卸载前移除事件监听
  window.removeEventListener('popstate', handlePopState);
});

// 添加格式化日期的方法
const formatDate = (dateString) => {
  if (!dateString) return '';
  
  // 替换T为空格，并保留日期和时间部分
  return dateString.replace('T', ' ').substring(0, 19);
};

// 添加预约对话框和相关功能
const bookingDialogVisible = ref(false);
const bookingFormRef = ref(null);
const bookingForm = ref({
  startTime: '',
  endTime: '',
  location: '',
  requirements: '',
  tutoringId: null
});
const bookingRules = {
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  location: [
    { required: true, message: '请输入上课地点', trigger: 'blur' }
  ],
  requirements: [
    { required: true, message: '请输入具体要求', trigger: 'blur' }
  ]
};
const submitBooking = async () => {
  if (!bookingFormRef.value) return;
  
  await bookingFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await tutoringService.createBooking(bookingForm.value)
        ElMessage.success('预约提交成功，等待教师确认')
        bookingDialogVisible.value = false
        bookingFormRef.value.resetFields()
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '预约失败')
      }
    }
  })
};
const resetBookingForm = () => {
  bookingFormRef.value.resetFields();
};

const showBookingDialog = (tutor) => {
  if (!tokenStore.token) {
    ElMessage.warning('请先登录');
    goToLogin();
    return;
  }
  
  // 检查用户角色，教师不能预约
  if (Number(tokenStore.userRole) === 1) {
    ElMessage.warning('教师不能预约其他教师的课程');
    return;
  }
  
  currentTutor.value = tutor;
  bookingForm.value.tutoringId = tutor.id;
  bookingDialogVisible.value = true;
};
</script>

<style scoped>
.home-container {
  width: 100%;
  font-family: Arial, sans-serif;
  background-color: #f5f5f5;
}

/* 顶部公告栏样式 */
.announcement {
  background-color: #fff;
  padding: 0;
  text-align: left;
  padding-left: 20px;
  border-bottom: 1px solid #eee;
  font-size: 14px;
  color: #333;
  height: 30px;
  line-height: 30px;
  overflow: hidden;
}

.announcement :deep(.el-carousel__item) {
  height: 30px;
  line-height: 30px;
}

.announcement-title {
  cursor: pointer;
  transition: color 0.3s;
}

.announcement-title:hover {
  color: #e60012;
}

.announcement-detail .announcement-meta {
  display: flex;
  justify-content: space-between;
  color: #909399;
  font-size: 14px;
  margin-bottom: 20px;
}

.announcement-detail .announcement-content {
  font-size: 16px;
  line-height: 1.6;
  color: #303133;
  white-space: pre-wrap;
}

/* 顶部导航栏样式 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background-color: #e60012;
  color: white;
}

.logo {
  display: flex;
  align-items: center;
}

.logo-img {
  height: 40px;
  margin-right: 10px;
}

.logo-text {
  font-size: 20px;
  font-weight: bold;
}

.nav-menu {
  display: flex;
  gap: 20px;
}

.nav-item {
  color: white;
  text-decoration: none;
  padding: 5px 10px;
  font-size: 16px;
}

.nav-item.active {
  font-weight: bold;
  border-bottom: 2px solid white;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-avatar {
  width: 40px;
  height: 40px;
}

.content-wrapper {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 20px;
}

/* 学科分类区域样式 */
.subject-categories {
  grid-column: 1 / 2;
  display: flex;
  flex-direction: column;
  gap: 15px;
  padding: 20px;
  background-color: white;
  border-radius: 5px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  margin-top: 20px;
}

.categories-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
}

.category-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15px;
  cursor: pointer;
  transition: transform 0.3s, box-shadow 0.3s;
  border-radius: 8px;
  background-color: #f9f9f9;
}

.category-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.subject-icon {
  width: 60px;
  height: 60px;
  margin-bottom: 10px;
  border-radius: 8px;
  overflow: hidden;
}

.category-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.category-name {
  font-weight: bold;
  font-size: 16px;
  color: #333;
  margin-bottom: 4px;
}

.category-alias {
  font-size: 12px;
  color: #666;
}

.empty-categories {
  padding: 30px 0;
}

/* 平台教师展示区域样式 - 右侧版本 */
.platform-teachers-right {
  grid-column: 2 / 3;
  grid-row: 1 / 2;
  display: flex;
  flex-direction: column;
  background-color: white;
  border-radius: 5px;
  padding: 20px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  margin-top: 20px;
}

.platform-teachers-right .teachers-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.platform-teachers-right .teacher-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
  transition: transform 0.3s, box-shadow 0.3s;
  cursor: pointer;
}

.platform-teachers-right .teacher-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.platform-teachers-right .teacher-avatar {
  margin-bottom: 10px;
}

.platform-teachers-right .teacher-avatar-img {
  width: 60px;
  height: 60px;
}

.platform-teachers-right .teacher-name {
  font-weight: bold;
  color: #333;
  margin: 5px 0;
  text-align: center;
}

.platform-teachers-right .teacher-subject {
  font-size: 12px;
  color: #666;
  margin: 0;
  text-align: center;
}

/* 中间轮播图区域样式 */
.banner-section {
  grid-column: 1 / 3;
  margin: 20px 0;
}

.banner-container {
  width: 100%;
}

.banner-image {
  width: 100%;
  height: 100%;
}

.banner-placeholder {
  width: 100%;
  height: 100%;
  background-color: #ffcc00;
  display: flex;
  align-items: center;
  justify-content: center;
}

.banner-text {
  text-align: center;
  color: #333;
}

.banner-text h2 {
  font-size: 36px;
  margin: 0;
}

/* 请家教/做家教按钮区域样式 */
.action-buttons {
  grid-column: 1 / 3;
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.action-button {
  flex: 1;
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 5px;
  color: white;
  font-size: 24px;
  cursor: pointer;
  transition: transform 0.3s;
}

.request-tutor {
  background-color: #4a7eb3;
}

.become-tutor {
  background-color: #5cb85c;
}

/* 登录区域样式 */
.login-section {
  grid-column: 2 / 3;
  grid-row: 2 / 3;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background-color: white;
  border-radius: 5px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  margin-top: 20px;
}

.login-logo {
  margin-bottom: 20px;
}

.logo-circle {
  width: 80px;
  height: 80px;
  background-color: #f0f0f0;
  border-radius: 50%;
}

.login-buttons {
  display: flex;
  flex-direction: column;
  gap: 10px;
  width: 100%;
  margin-bottom: 20px;
}

.login-btn {
  width: 100%;
  padding: 10px;
  border: none;
  border-radius: 4px;
  color: white;
  font-size: 16px;
  cursor: pointer;
}

.parent-btn {
  background-color: #67c23a;
}

.teacher-btn {
  background-color: #f56c6c;
}

.qrcode-container {
  text-align: center;
}

.qrcode-placeholder {
  width: 120px;
  height: 120px;
  background-color: #f0f0f0;
  margin: 0 auto 10px;
}

/* 移除旧的平台教师样式 */
/* 
.platform-teachers {
  grid-column: 1 / 3;
  margin-top: 30px;
  background-color: white;
  border-radius: 5px;
  padding: 20px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.teachers-list {
  display: flex;
  justify-content: space-between;
}

.teacher-card {
  width: 18%;
  text-align: center;
}

.teacher-avatar-placeholder {
  width: 80px;
  height: 80px;
  background-color: #f0f0f0;
  border-radius: 50%;
  margin: 0 auto 10px;
}

.teacher-name {
  font-weight: bold;
  color: #333;
}
*/

.section-title {
  position: relative;
  padding-left: 15px;
  margin-bottom: 20px;
  font-size: 20px;
  color: #333;
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 5px;
  height: 20px;
  background-color: #e60012;
}

/* 平台统计数据样式 */
.platform-stats {
  grid-column: 1 / 3;
  margin-top: 30px;
  background-color: white;
  border-radius: 5px;
  padding: 20px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.stats-container {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.stat-item {
  text-align: center;
  width: 22%;
  padding: 15px;
  border-radius: 5px;
  background-color: #f9f9f9;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #e60012;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

/* 底部区域样式 */
.footer {
  margin-top: 30px;
  padding: 20px;
  text-align: center;
  background-color: #f5f5f5;
  color: #666;
  border-top: 1px solid #eee;
}

@media (max-width: 768px) {
  .content-wrapper {
    grid-template-columns: 1fr;
  }
  
  .subject-categories,
  .platform-teachers-right,
  .login-section,
  .banner-section,
  .action-buttons,
  .platform-stats {
    grid-column: 1;
  }
  
  .platform-teachers-right {
    grid-row: auto;
  }
  
  .login-section {
    grid-row: auto;
  }
  
  .platform-teachers-right .teachers-list {
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-between;
  }
  
  .platform-teachers-right .teacher-card {
    width: 48%;
    margin-bottom: 10px;
  }
  
  .stats-container {
    flex-wrap: wrap;
    gap: 10px;
  }
  
  .stat-item {
    width: 45%;
    margin-bottom: 10px;
  }
}

/* 骨架屏样式 */
.skeleton {
  background-color: #f5f5f5;
  border-radius: 8px;
}

.skeleton-icon {
  width: 60px;
  height: 60px;
  background-color: #e0e0e0;
  border-radius: 8px;
  margin-bottom: 10px;
}

.skeleton-text {
  width: 80%;
  height: 16px;
  background-color: #e0e0e0;
  border-radius: 4px;
  margin-bottom: 8px;
}

.skeleton-text-sm {
  width: 60%;
  height: 12px;
  background-color: #e0e0e0;
  border-radius: 4px;
}

/* 图片错误样式 */
.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
  color: #909399;
  font-size: 20px;
}

/* 错误信息样式 */
.error-message {
  margin-top: 10px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .el-row {
    margin-left: 0 !important;
    margin-right: 0 !important;
  }
  
  .el-col {
    padding-left: 0 !important;
    padding-right: 0 !important;
  }
  
  .video-card {
    margin-bottom: 15px;
  }
  
  .video-thumbnail {
    height: 150px;
  }
}

.category-tip {
  font-size: 14px;
  color: #666;
  margin-bottom: 15px;
  text-align: center;
}

/* 分类视频区域样式 */
.category-videos-section {
  grid-column: 1 / 3;
  width: 100%;
  margin-top: 0;
  background-color: white;
  border-radius: 5px;
  padding: 20px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.lesson-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  padding: 20px 0;
}

.lesson-card {
  cursor: pointer;
  transition: transform 0.3s, box-shadow 0.3s;
  position: relative;
  height: 100%;
}

.lesson-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.lesson-cover {
  position: relative;
  height: 160px;
  overflow: hidden;
}

.lesson-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.lesson-cover .play-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 50px;
  height: 50px;
  background-color: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  font-size: 24px;
  opacity: 0.8;
  transition: opacity 0.3s, transform 0.3s;
}

.lesson-card:hover .lesson-cover .play-icon {
  opacity: 1;
  transform: translate(-50%, -50%) scale(1.1);
}

.lesson-info {
  padding: 12px;
}

.lesson-title {
  margin: 0 0 8px;
  font-size: 16px;
  font-weight: bold;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.lesson-meta {
  display: flex;
  justify-content: space-between;
  color: #666;
  font-size: 12px;
}

.lesson-stats {
  display: flex;
  justify-content: space-between;
  color: #666;
  font-size: 12px;
  margin-top: 8px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.loading-container {
  padding: 20px 0;
}

.video-detail .detail-meta {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  color: #666;
  font-size: 14px;
}

.video-detail .video-player-container {
  margin-bottom: 20px;
  background: #f5f5f5;
  border-radius: 4px;
  overflow: hidden;
}

.video-detail .detail-content {
  line-height: 1.6;
  color: #303133;
  margin-top: 20px;
}

.video-player {
  width: 100%;
  max-height: 70vh;
}

.empty-videos {
  padding: 30px 0;
  text-align: center;
}

.back-button-container {
  margin-bottom: 20px;
  grid-column: 1 / 3;
  width: 100%;
}

/* 家教广场样式 */
.tutoring-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  grid-column: 1 / 3;
  width: 100%;
}

.main-title {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.tutoring-list {
  grid-column: 1 / 3;
  width: 100%;
}

.tutoring-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.tutoring-card {
  border-radius: 8px;
  transition: transform 0.3s, box-shadow 0.3s;
}

.tutoring-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.tutor-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.tutor-avatar {
  width: 60px;
  height: 60px;
  margin-right: 15px;
}

.tutor-info {
  flex: 1;
}

.tutor-name {
  margin: 0 0 5px 0;
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.tutor-subjects {
  color: #e60012;
  font-size: 14px;
}

.tutor-edu {
  color: #666;
  font-size: 12px;
}

.tutor-description {
  margin-bottom: 15px;
  font-size: 14px;
  color: #555;
  line-height: 1.5;
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.tutor-details {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.detail-item {
  margin-bottom: 8px;
  font-size: 14px;
  display: flex;
}

.detail-label {
  color: #666;
  margin-right: 5px;
  min-width: 70px;
}

.price {
  color: #e60012;
  font-weight: bold;
}

.tutor-action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 10px;
}

.empty-tutoring {
  grid-column: 1 / 3;
  padding: 30px 0;
}

/* 老师详情对话框样式 */
.tutor-detail-dialog {
  padding: 10px;
}

.tutor-detail-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.tutor-detail-avatar {
  width: 80px;
  height: 80px;
  margin-right: 15px;
}

.tutor-detail-info {
  flex: 1;
}

.tutor-detail-name {
  margin: 0 0 5px 0;
  font-size: 22px;
  font-weight: 600;
}

.tutor-detail-subjects {
  color: #409EFF;
  margin-bottom: 5px;
  font-size: 16px;
}

.tutor-detail-edu {
  color: #606266;
  font-size: 14px;
}

.tutor-detail-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f7f9fc;
  border-radius: 8px;
}

.section-subtitle {
  margin: 0 0 10px 0;
  font-size: 18px;
  color: #303133;
  border-left: 4px solid #409EFF;
  padding-left: 10px;
}

.tutor-detail-description {
  line-height: 1.6;
  white-space: pre-wrap;
}

.tutor-detail-item {
  margin-bottom: 8px;
  line-height: 1.6;
}

.tutor-detail-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 调整卡片中显示的信息量 */
.tutor-details {
  max-height: 150px;
  overflow: hidden;
  position: relative;
}

.tutor-details::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 30px;
  background: linear-gradient(transparent, white);
}

.el-dropdown__box {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 5px 10px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.el-dropdown__box:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.username {
  margin-left: 8px;
  color: white;
  font-size: 14px;
}

/* 留言反馈样式 */
.feedback-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px 0;
  grid-column: 1 / 3;
  width: 100%;
}

.feedback-title {
  font-size: 24px;
  color: #303133;
  margin-bottom: 10px;
  text-align: center;
}

.feedback-desc {
  color: #606266;
  font-size: 14px;
  text-align: center;
  margin-bottom: 20px;
}

.feedback-form-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 30px;
}

.feedback-history {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.history-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.feedback-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.feedback-content {
  margin-bottom: 15px;
  white-space: pre-wrap;
  line-height: 1.5;
}

.feedback-reply {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-top: 15px;
}

.reply-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.reply-title {
  font-weight: bold;
  color: #409EFF;
}

.reply-time {
  font-size: 12px;
  color: #909399;
}

.reply-content {
  white-space: pre-wrap;
  line-height: 1.5;
  margin-bottom: 10px;
}

.reply-footer {
  text-align: right;
  font-size: 12px;
  color: #909399;
}

.feedback-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

/* 调整留言反馈区域的布局 */
.feedback-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.feedback-form-container,
.feedback-history {
  width: 100%;
  max-width: 800px;
}

/* 系统公告样式 */
.announcements-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px 0;
  grid-column: 1 / 3;
  width: 100%;
}

.announcements-title {
  font-size: 24px;
  color: #303133;
  margin-bottom: 10px;
  text-align: center;
}

.announcements-desc {
  color: #606266;
  font-size: 14px;
  text-align: center;
  margin-bottom: 20px;
}

.announcements-list-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.list-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.announcement-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.announcement-card-title {
  font-weight: bold;
  font-size: 16px;
}

.announcement-card-content {
  margin: 15px 0;
  white-space: pre-wrap;
  line-height: 1.6;
}

.announcement-card-footer {
  text-align: right;
  font-size: 12px;
  color: #909399;
}

.announcements-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.announcements-list-container {
  width: 100%;
  max-width: 800px;
}
</style>
